﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Text.RegularExpressions;

using Kenly.ChineseSegment;
using Kenly.ChineseSegment.Core;
using Kenly.ChineseSegment.DictionaryLoader;
using Kenly.ChineseSegment.DictionaryWriter;

namespace SegmentTool
{


    public partial class frmMain : Form
    {
        IWordSegment _wordSegment = new ForwardMatchSegment();
        IDictionaryLoader _loader = new TextDictionaryLoader();

        public frmMain()
        {
            InitializeComponent();

            LoadDictionary();
        }


        private void frmMain_Load(object sender, EventArgs e)
        {
            lblTextLength.Text = txtSrc.Text.Length.ToString();
        }

        private void txtSrc_TextChanged(object sender, EventArgs e)
        {
            lblTextLength.Text = txtSrc.Text.Length.ToString();
        }

        private void toolStripButtonSegment_Click(object sender, EventArgs e)
        {
            Segment(_loader);
        }

        private void toolStripButtonAppend_Click(object sender, EventArgs e)
        {
            AddToDict();
        }

        private void toolStripButtonLoadDict_Click(object sender, EventArgs e)
        {
            LoadDictionary();
        }

        private void LoadDictionary()
        {
            string baseDictionaryPath = Application.StartupPath + @"\Dict\txt\BaseDict.txt";
            string customDictPath = Application.StartupPath + @"\Dict\txt\CustomDict.txt"; //自定义词库

            string nameDictionaryPath = Application.StartupPath + @"\Dict\txt\familyname.txt";
            string numberDictionaryPath = Application.StartupPath + @"\Dict\txt\number.txt";


            DateTime startTime = DateTime.Now;

            //加载基本词库
            _wordSegment.LoadDictionary(_loader, baseDictionaryPath);

            _wordSegment.AppendDictionary(_loader, customDictPath);

            _wordSegment.LoadNumberDictionary(_loader, numberDictionaryPath);
            _wordSegment.LoadNameDictionary(_loader, nameDictionaryPath);


            TimeSpan timeSpan = DateTime.Now - startTime;

            lblLoadDictTime.Text = timeSpan.TotalMilliseconds.ToString();
        }

        private void Segment(IDictionaryLoader loader)
        {
            DateTime startTime = DateTime.Now;

            string filterFilePath = Application.StartupPath + @"\Dict\txt\Filter.txt";

            //文本预处理
            string text = TextProcess.Filter(txtSrc.Text, filterFilePath, loader);

            _wordSegment.Separator = " ";

            //分词
            string titleResult = _wordSegment.Segment(txtTitle.Text);
            string bodyResult = _wordSegment.Segment(text);

            txtResult.Text = titleResult+"\r\n"+bodyResult;

            TimeSpan timeSpan = DateTime.Now - startTime;

            lblSegmentTime.Text = timeSpan.TotalMilliseconds.ToString();


            startTime = DateTime.Now;

            //统计词频
            List<SegmentCounter> bodyCounters = SegmentCounter.Count(bodyResult,_wordSegment.Separator);
            List<SegmentCounter> titleCounters = SegmentCounter.Count(titleResult, bodyCounters.Count,40, _wordSegment.Separator);

            List<SegmentCounter> allCounters = bodyCounters;
            SegmentCounter.Merge(ref allCounters, titleCounters);
            allCounters.Sort();

            timeSpan = DateTime.Now - startTime;
            lblSegmentTime.Text =lblSegmentTime.Text+" 统计:"+ timeSpan.TotalMilliseconds.ToString();

            listView1.Items.Clear();
            foreach (SegmentCounter segmentCounter in allCounters)
            {
                listView1.Items.Add(segmentCounter.Segment);
                listView1.Items[listView1.Items.Count - 1].SubItems.Add(segmentCounter.Times.ToString());
                listView1.Items[listView1.Items.Count - 1].SubItems.Add(segmentCounter.Rank.ToString());
            }

            List<string> unknownList = new List<string>();
            List<WordFrequence> words = Training.RecognizeWords(text);
            foreach (WordFrequence word in words)
            {
                if (!_wordSegment.SegmentDictionary.SegmentList.Contains(word.Word))
                {
                    unknownList.Add(word.Word);
                }
            }
            //RegexHelper.ExtractUnknownChinese(unknownList, txtResult.Text);
            DisplayUnknownChinese(unknownList);
        }

        private void DisplayUnknownChinese(List<string> unknownList)
        {
            if (unknownList == null || unknownList.Count <= 0)
            {
                return;
            }

            StringBuilder unknownChinese = new StringBuilder();
            foreach (string item in unknownList)
            {
                unknownChinese.Append(item + " ");
            }

            unknownChinese.Remove(unknownChinese.Length - 1, 1);

            txtResult.Text += "\r\n\r\n未能识别的候选新词：\r\n";
            txtResult.Text += unknownChinese.ToString();
        }

        private void AddToDict()
        {
            string selectedText = !string.IsNullOrEmpty(txtSrc.SelectedText) ?
                txtSrc.SelectedText : txtResult.SelectedText;

            Regex regex = new Regex(@"\s");
            selectedText = regex.Replace(selectedText, "");

            if (!CheckSelectedText(selectedText))
            {
                return;
            }

            DialogResult result = MessageBox.Show("确定把 \""+selectedText+"\" 加入自定义词库吗？",
                  "加入自定义词库", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.No)
            {
                return;
            }

            string customDictPath = Application.StartupPath + @"\Dict\txt\CustomDict.txt";
            IDictionaryWriter dictionaryWriter = new TextDictionaryWriter();

            List<string> segmentList = new List<string>();
            segmentList.Add(selectedText);

            bool r = dictionaryWriter.Append(customDictPath, segmentList);
            MessageBox.Show(r ? "加入自定义词库成功。" : "加入自定义词库失败！", "加入自定义词库",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private bool CheckSelectedText(string selectedText)
        {
            if (string.IsNullOrEmpty(selectedText))
            {
                MessageBox.Show("请选择需要加入自定义词库的词语!",
                    "加入自定义词库", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            if (_wordSegment.SegmentDictionary.SegmentList.Contains(selectedText))
            {
                MessageBox.Show("\""+selectedText + "\" 在词库中已存在!",
                    "加入自定义词库", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }

        private void dicFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmDicFilter frmDicFilterObj = new frmDicFilter();
            frmDicFilterObj.ShowDialog();
        }
    }
}
